package com.banciyuan.bcywebview.biz.main.discover.topwork;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.api.IllustApi;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.TypeSet;

import static com.banciyuan.bcywebview.R.id.minus_date;


public class TopWorkActivity extends BaseActivity implements View.OnClickListener, BaseWatcher {

    private boolean loading;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");

    protected TabLayout mTabLayout;
    private ViewPager mViewPager;
    private String mRankType;
    private ImageView minusDate;
    private ImageView plusDate;
    private TextView rankDate;

    protected SparseArray<Fragment> mTopWorkFragments = new SparseArray<>();
    protected List<TypeSet> mTypeSets = new ArrayList<>();
    protected String date;
    protected String today;
    protected String last_day = "20151001";

    public static final int COS_TYPE = 0;
    public static final int ILLUST_TYPE = 1;
    public static final int NOVEL_TYPE = 2;
    private int mType = ILLUST_TYPE;

    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.top_work_activity);
        initArgs();
        initUi();
        initActionbar();
        initAction();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseObserver.getInstance().addWatcher(TopWorkActivity.class, this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseObserver.getInstance().removeWatcher(TopWorkActivity.class);
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        mType = intent.getIntExtra(gotoUtil.INTENT_VALUE_ONE, ILLUST_TYPE);
        mRankType = intent.getStringExtra(gotoUtil.INTENT_VALUE_TWO);
        date = intent.getStringExtra(gotoUtil.INTENT_VALUE_THREE);
        if (mType == ILLUST_TYPE)
            url = HttpUtils.BASE_URL + IllustApi.getRankTypes();
        else if (mType == COS_TYPE)
            url = HttpUtils.BASE_URL + CoserApi.getRankTypes();
        else if (mType == NOVEL_TYPE)
            url = HttpUtils.BASE_URL + NovelApi.getRankTypes();
    }

    @Override
    protected void initActionbar() {
        View mActionBarView = findViewById(R.id.base_action_bar);
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        if (mType == ILLUST_TYPE) {
            mActionbarHelper.setTitle(getString(R.string.draw_rank));
        } else if (mType == COS_TYPE) {
            mActionbarHelper.setTitle(getString(R.string.cos_rank));
        } else if (mType == NOVEL_TYPE) {
            mActionbarHelper.setTitle(getString(R.string.write_rank));
        }
    }

    @Override
    protected void initUi() {
        mTabLayout = (TabLayout) findViewById(R.id.tablayout);
        mViewPager = (ViewPager) findViewById(R.id.mViewpager);
        minusDate = (ImageView) findViewById(minus_date);
        plusDate = (ImageView) findViewById(R.id.plus_date);
        rankDate = (TextView) findViewById(R.id.rank_date);
        minusDate.setOnClickListener(this);
        plusDate.setOnClickListener(this);
        setTabLayoutMode();
        if (StringUtil.notNullEqual(mRankType, "pay")) {
            ((View) (minusDate.getParent())).setVisibility(View.GONE);
        } else {
            ((View) (minusDate.getParent())).setVisibility(View.VISIBLE);
        }
    }


    protected void setTabLayoutMode() {
        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

    @Override
    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<>();
        Map<String, String> map = HttpUtils.getData(paramsList);
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, TopWorkActivity.this)) {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONObject object = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        mTypeSets = gson.fromJson(object.getString("type_set"), new TypeToken<List<TypeSet>>() {
                        }.getType());
                        today = object.getString("date");
                        if (TextUtils.isEmpty(date)) {
                            date = today;
                        }
                        processData();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSuccess, url, this, map);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onSuccess, errorProxy);
        VolleyQueue.getRquest(this).add(getUserdataRequest);
    }

    private void processData() {
        if (!TextUtils.isEmpty(date)) {
            try {
                rankDate.setText(sdf2.format(sdf.parse(date)));
                setCalenderDate();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        mViewPager.setOffscreenPageLimit(mTypeSets.size());
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return getTopWorkFragment(position);
            }

            @Override
            public int getCount() {
                return mTypeSets.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mTypeSets.get(position).getName();
            }
        });
        mTabLayout.setupWithViewPager(mViewPager);
        for (int i = 0; i < mTypeSets.size(); i++) {
            if (mRankType.equals(mTypeSets.get(i).getType())) {
                mViewPager.setCurrentItem(i);
                break;
            }
        }

        mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                if (StringUtil.notNullEqual(mTypeSets.get(tab.getPosition()).getType(), "pay")) {
                    ((View) (minusDate.getParent())).setVisibility(View.GONE);
                } else {
                    ((View) (minusDate.getParent())).setVisibility(View.VISIBLE);
                }
            }
        });
    }

    protected Fragment getTopWorkFragment(int position) {
        Fragment currentFragment = mTopWorkFragments.get(position);
        if (null == currentFragment) {
            currentFragment = new TopWorkFragment();
            Bundle bundle = new Bundle();
            bundle.putInt(gotoUtil.INTENT_VALUE_ONE, mType);
            bundle.putString(gotoUtil.INTENT_VALUE_TWO, mTypeSets.get(position).getType());
            bundle.putString(gotoUtil.INTENT_VALUE_THREE, date);
            currentFragment.setArguments(bundle);
            mTopWorkFragments.put(position, currentFragment);
        }
        return currentFragment;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_action_bar_home:
                finish();
                break;
            case R.id.minus_date:
                if (parseDate(-1)) {
                    FragmentUpdate();
                }
                break;
            case R.id.plus_date:
                if (parseDate(1)) {
                    FragmentUpdate();
                }
                break;
        }
    }

    private boolean parseDate(int move) {
        if (loading || TextUtils.isEmpty(today) || TextUtils.isEmpty(date)) return false;
        loading = true;
        try {
            Date todays = sdf.parse(today);
            Date lastDay = sdf.parse(last_day);
            Date server_date = sdf.parse(date);
            if ((server_date.equals(todays) || server_date.after(todays)) && move > 0) {
                loading = false;
                return false;
            }
            if ((lastDay.equals(server_date) || server_date.before(lastDay)) && move < 0) {
                loading = false;
                return false;
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(server_date);
            calendar.add(Calendar.DATE, move);
            date = sdf.format(calendar.getTime());
            rankDate.setText(sdf2.format(calendar.getTime()));
            setCalenderDate();
            return true;
        } catch (ParseException e) {
            loading = false;
            return false;
        }
    }

    private void setCalenderDate() {
        if (date.equals(today)) {
            plusDate.setVisibility(View.INVISIBLE);
        } else {
            plusDate.setVisibility(View.VISIBLE);
        }
        if (date.equals(last_day)) {
            minusDate.setVisibility(View.INVISIBLE);
        } else {
            minusDate.setVisibility(View.VISIBLE);
        }
    }

    private void FragmentUpdate() {
        for (int i = 0; i < mTopWorkFragments.size(); i++) {
            BaseLazyContainerFragment f = (BaseLazyContainerFragment) mTopWorkFragments.valueAt(i);
            if (f instanceof TopWorkFragment) {
                TopWorkFragment t = (TopWorkFragment) f;
                t.setDate(date);
            } else if (f instanceof NovelTopWorkFragment) {
                NovelTopWorkFragment n = (NovelTopWorkFragment) f;
                n.setDate(date);
            }
            if (f.isVisibleToUser()) {
                f.selfUpdateData();
            } else {
                if (!StringUtil.notNullEqual(mTypeSets.get(i).getType(), "pay")) {
                    f.setDataInitiated(false);
                    if (f instanceof TopWorkFragment) {
                        ((TopWorkFragment) f).resetUi();
                    } else if (f instanceof NovelTopWorkFragment) {
                        ((NovelTopWorkFragment) f).resetUi();
                    }
                }
            }

        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }

    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        switch (eventCode) {
            case BaseObserver.RANK_REFREASH:
                loading = false;
                break;
        }
    }
}
